/**
 * @filename:ItemController 2021-11-09 01:40:37
 * @project com/lwl/blue  V1.0
 * Copyright(c) 2020 <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a> Co. Ltd.
 * All right reserved.
 */
package com.lwl.blue.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.commont.enums.SourceTypeEnum;
import com.lwl.blue.commont.utils.ComputingFormulaUtil;
import com.lwl.blue.commont.utils.EasyExcelUtils;
import com.lwl.blue.commont.utils.ParamsCheckUtilService;
import com.lwl.blue.commont.utils.UserContextUtil;
import com.lwl.blue.entity.Item;
import com.lwl.blue.excel.item.ItemExport;
import com.lwl.blue.excel.item.ItemImport;
import com.lwl.blue.service.FilesService;
import com.lwl.blue.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * <p>自定义方法写在这里</p>
 *
 * <p>说明： 产品API接口层</P>
 *
 * @version: V1.0
 * @author: <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a>
 */
@RestController
@RequestMapping("/item")
@Slf4j
public class ItemController extends BaseController {
    @Value("${export.file.path.prefix}")
    private String prefix;
    @Autowired
    ItemService itemService;
    @Resource
    ParamsCheckUtilService paramsCheckUtil;
    @Resource
    FilesService filesService;

    @PostMapping("/pages")
    public PageResult<Item> getPages(@RequestBody PageParam<Item> pageParam) {
        JsonResult<Page<Item>> pages = itemService.pages(pageParam);
        PageResult<Item> re = new PageResult<>();
        re.success(pages.getData().getTotal(), pages.getData().getRecords());
        return re;
    }

    @PostMapping("saveOrUpdate")
    public JsonResult saveOrUpdate(@RequestBody Item item) {
        setInsetOrUpdateUser(item);
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Item::getItemNo, item.getItemNo())
                .eq(Item::getIsDelete, 0);
        Item item1 = null;
        if (null != item.getId()) {
            wrapper.lambda().notIn(Item::getId, item.getId());
            item1 = itemService.getById(item.getId());
        }
        int count = itemService.count(wrapper);
        if (count > 0) {
            throw new BizException(ErrorCode.DATA_EXISTS_ERROR.getCode(), ErrorCode.DATA_EXISTS_ERROR.getMsg() + item.getItemNo());
        }
        itemService.saveOrUpdate(item);
        filesService.updateBySaveOrUpdate(item.getPhoto(), item1 == null ? null : item1.getPhoto(), item.getId(), item.getItemNo());
        return new JsonResult().success("请求成功");
    }

    @PostMapping("/delete/{id}")
    public JsonResult delete(@PathVariable(value = "id") Integer id) {
        itemService.update(new UpdateWrapper<Item>().lambda()
                .set(Item::getIsDelete, Const.IS_DELETE_YES)
                .set(Item::getUpdateUser, UserContextUtil.getUser().getUserName())
                .eq(Item::getId, id));
        return new JsonResult().success("请求成功");
    }

    @PostMapping("/deleteByIds")
    public JsonResult deleteByIds(@RequestBody List<Integer> ids) {
        itemService.update(new UpdateWrapper<Item>().lambda()
                .set(Item::getIsDelete, Const.IS_DELETE_YES)
                .in(Item::getId, ids));
        return new JsonResult().success("请求成功");
    }

    @PostMapping("/select")
    public JsonResult select() {
        List<Item> reList = itemService.list(new QueryWrapper<Item>()
                .lambda().eq(Item::getIsDelete, 0));
        return new JsonResult().success(reList);
    }

    @PostMapping("/getById/{id}")
    public JsonResult getById(@PathVariable(value = "id") Integer id) {
        return itemService.getItemById(id);
    }

    @GetMapping("/export/{params}")
    public void export(HttpServletResponse response, @PathVariable("params") String params) throws IOException {
        Item item = JSON.parseObject(params, Item.class);
        List<Item> reList = itemService.getExportList(item);
        List<ItemExport> itemExports = new ArrayList<>();
        if (!reList.isEmpty()) {
            reList.forEach(
                    l -> {
                        ItemExport itemExport = new ItemExport();
                        BeanUtils.copyProperties(l, itemExport, "photo");
                        if (StringUtils.isNotEmpty(l.getPhoto())) {
                            URL url = EasyExcelUtils.getURL(l.getPhoto());
                            itemExport.setPhoto(url);
                        }
                        if (StringUtils.isNotEmpty(l.getIsTax())) {
                            if ("是".equals(l.getIsTax())) {
                                l.setIsTax("yes");
                            } else if ("否".equals(l.getIsTax())) {
                                l.setIsTax("no");
                            }
                        }
                        itemExports.add(itemExport);
                    }
            );
        }
        EasyExcelUtils.export(response, "产品", ItemExport.class, itemExports);
    }

    @RequestMapping(value = "/importItem", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importItem(@RequestParam("file") MultipartFile uploadFile) {
        InputStream inputStream = null;
        List<Item> addList = new ArrayList<>();
        try {
            inputStream = uploadFile.getInputStream();
            List<ItemImport> itemList = EasyExcelFactory.read(inputStream).sheet(0).headRowNumber(3).head(ItemImport.class).doReadSync();
            Set<String> set = new HashSet<>();
            itemList.forEach(i -> {
                //校验
                if (set.contains(i.getItemNo())) {
                    throw new BizException(ErrorCode.DATA_REPEAT_ERROR.getCode(), ErrorCode.DATA_REPEAT_ERROR.getMsg() + i.getItemNo());
                }
                set.add(i.getItemNo());
                Item add = new Item();
                paramsCheckUtil.checkObject(i);
                BeanUtils.copyProperties(i, add);
                add.setCubeNumber(ComputingFormulaUtil.cubicNumber(add.getBoxSizeLength(), add.getBoxSizeWidth(), add.getBoxSizeHeight()));
                add.setJustCount(ComputingFormulaUtil.justCount(add.getCubeNumber()));
                if (null != add.getBoxNumber() && null != add.getItemWeight()) {
                    add.setBoxSuttle(add.getBoxNumber().multiply(add.getItemWeight()));
                }
                //判断新增的是否已经存在相同的编号
                LambdaQueryWrapper<Item> wrapper = new QueryWrapper<Item>().lambda().eq(Item::getItemNo, add.getItemNo()).eq(Item::getIsDelete, 0);
                if (null != add.getItemNo()) {
                    wrapper.notIn(Item::getId, add.getId());
                }
                int count = itemService.count(wrapper);
                if (count > 0) {
                    throw new BizException(ErrorCode.DATA_EXISTS_ERROR.getCode(), ErrorCode.DATA_EXISTS_ERROR.getMsg() + add.getItemNo());
                }
                addList.add(add);
            });
            itemService.saveOrUpdateBatch(addList);
            return new JsonResult().success("产品导入成功");
        } catch (IOException e) {
            log.error("文件上传异常：{}，异常信息：{}", e, e.getMessage());
            return new JsonResult().error(e.getMessage());
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("文件上传关闭异常：{}，异常信息：{}", e, e.getMessage());
                }
            }
        }
    }
}
